#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "logger.h"

#define DIM_MESSAGE	100

static FILE * getFile(void)
{
	FILE * logFile;
	if((logFile= fopen(LOGFILE, "a+")) != NULL)
		return logFile;
	else
		return NULL;
}

static int loggerWrite(const char * info, FILE * logFile)
{
	time_t actTime;
	char * outString, * actDate;
	
	if (logFile == NULL || info == NULL)
		return 0;
	
	time(&actTime);	
	actDate=ctime(&actTime);	
	
	actDate[strlen(actDate) - 1]='\0';
		
	if((outString = ((char *) malloc(strlen(info) + strlen(actDate) + DIM_MESSAGE))) != NULL)
	{
		sprintf(outString, "INFO: %s -> %s\n", actDate, info);
		fprintf(logFile, outString );
		free(outString);
	}
	else
		return 0;
	
	return 1;
	
}

int logAction(const char * info)
{
	FILE * file;
	
	if(info == NULL)
	{
		fprintf(stderr,"WARNING: Illegal logging.\n");
		return 0;
	}
	
	if((file = getFile()) == NULL)
	{
		fprintf(stderr,"ERROR: Logging file couldn't be written.\n");
		return 0;
	}
	
	loggerWrite(info, file);
	fclose(file);
	return 1;
}

